package ch3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁使用方法示例
 */

public class ReadWriteLockUsage {
    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();
    private final Lock writeLock = rwLock.writeLock();

    // 读线程调用此方法
    public void reader() {
        readLock.lock();
        try {
            // 读取共享变量
        } finally {
            readLock.unlock();
        }
    }

    // 写线程执行该方法
    public void writer() {
        writeLock.lock();
        try {
            // 读写共享变量
        } finally {
            writeLock.unlock();
        }
    }
}
